package Seity;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedList;

import org.ictclas4j.bean.SegResult;
import org.ictclas4j.segment.SegTag;

/**
 * This class reads all files in a directory and output the split results into
 * another directory.
 * 
 * @author Xu Sheng
 * @version 1.0.0
 */
public class Participle {

	SegTag segTag;

	public Participle() {
		segTag = new SegTag(1);
	}

	public void split(String src, String dest) {
		File file = null;
		BufferedReader input = null;
		PrintWriter output = null;
		String line = null;

		try {
			input = new BufferedReader(new InputStreamReader(
					new FileInputStream(new File(src))));
			file = new File(dest);
			file.createNewFile();
			output = new PrintWriter(new FileOutputStream(file));

			line = input.readLine();
			output.write(line + "\r\n");
			while ((line = input.readLine()) != null) {
				SegResult segRes = segTag.split(line);
				output.write(segRes.getFinalResult() + "\r\n");
			}

		} catch (FileNotFoundException e) {
			System.err.println("File " + src + " not found when reading...");
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("Failed to create file " + dest + "...");
			e.printStackTrace();
		} finally {
			if (input != null)
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (output != null)
				output.close();
		}
	}

	public void splitAll(String src, String dest) {
		LinkedList<File> list = new LinkedList<File>();
		File dir = new File(src);
		File file[] = dir.listFiles();
		for (int i = 0; i < file.length; i++) {
			if (file[i].isDirectory())
				list.add(file[i]);
			else
				split(file[i].getAbsolutePath(), dest + "/" + file[i].getName());
		}
		File tmp, folder;
		while (!list.isEmpty()) {
			tmp = list.removeFirst();
			folder = new File(dest + "/" + tmp.getName());
			folder.mkdir();
			splitAll(tmp.getAbsolutePath(), dest + "/" + tmp.getName());
		}
	}

	public static void main(String[] args) {
		Participle p = new Participle();
		p.splitAll("E:/TEMP/temp1", "E:/TEMP/temp2");
	}
}
